package com.hk.kindheartedness;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.hk.kindheartedness.db.DBOpenHelper;
import com.hk.kindheartedness.model.User;
import com.hk.kindheartedness.model.vo.DoctorVo;
import com.hk.kindheartedness.util.DateUtil;
import com.hk.kindheartedness.util.RegexUtil;
import com.hk.kindheartedness.util.ToastUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 修改医生信息
 */
public class DoctorUpdateActivity extends AppCompatActivity implements View.OnClickListener {

    //    Initialize Toast
    private Toast toast;

    //    Initialize intent
    private Intent intent;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    //  Initialize button
    private Button updateDoctorBtn;

    private EditText userName,phone,idNumber,age,address,specialty,describe;

    private TextView doctorId;

    private RadioButton man,woman;

    private Spinner positionType,departmentsType;

    //    声明全局医生职务和所属科室
    private String positionTypeToStr,departmentsTypeToStr;

    private Handler handler;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doctor_update);
//        实例化
        dbOpenHelper = new DBOpenHelper(DoctorUpdateActivity.this, "db_kindheartedness", null, 1);
        //        获取采购员信息控制权
        doctorId = findViewById(R.id.doctorId);
        userName = findViewById(R.id.userName);
        phone = findViewById(R.id.phone);
        idNumber = findViewById(R.id.idNumber);
        age = findViewById(R.id.age);
        address = findViewById(R.id.address);
//         获取性别控制权
        man = findViewById(R.id.man);
        woman = findViewById(R.id.woman);
        specialty = findViewById(R.id.specialty);
        describe = findViewById(R.id.describe);
        positionType = findViewById(R.id.positionType);
        departmentsType = findViewById(R.id.departmentsType);
//        获取更新按钮控制权
        updateDoctorBtn = findViewById(R.id.updateDoctorBtn);
        updateDoctorBtn.setOnClickListener(this);
        //        提取回显的采购员详情
        Intent intent2 = getIntent();
        Bundle bundle = intent2.getExtras();
//        回显获取的医生信息
        echoBuyerDoctor(bundle);
    }

    /**
     * 获取医生详情数据
     * @param bundle
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void echoBuyerDoctor(Bundle bundle) {
        if (Objects.isNull(bundle)) {
            toast = ToastUtil.toastHint(toast,DoctorUpdateActivity.this,"获取对象信息失败,请重试！");
            return;
        }
        String doctorVoToString = (String) bundle.get("doctorVo");
        if (Objects.nonNull(doctorVoToString)) {
            DoctorVo doctorVo = JSON.parseObject(doctorVoToString, DoctorVo.class);
//                进行回显
            doctorId.setText(doctorVo.getDoctorId().toString());
            userName.setText(doctorVo.getDoctorName());
            phone.setText(doctorVo.getPhone());
            idNumber.setText(doctorVo.getIdNumber());
            age.setText(doctorVo.getAge().toString());
//                进行性别判断
            if (doctorVo.getSex() == 0) {
                man.setChecked(true);
            } else {
                woman.setChecked(true);
            }
            address.setText(doctorVo.getAddress());
            specialty.setText(doctorVo.getSpecialty());
            describe.setText(doctorVo.getDescribe());

//            提取所属医生对应职务名称和所属科室名称
            String positionName = doctorVo.getPositionName();
            String departmentsName = doctorVo.getDepartmentsName();

//            查询所有职务
            findAllPosition(positionName);
//            查询所有二级科室
            findAllDepartments(departmentsName);

            positionType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    positionTypeToStr = (String) positionType.getSelectedItem();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {}
            });

            departmentsType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    departmentsTypeToStr = (String) departmentsType.getSelectedItem();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {}
            });


            return;
        }
        toast = ToastUtil.toastHint(toast,DoctorUpdateActivity.this,"获取对象信息失败,请重试！");
        return;


    }

    /**
     * 查询所有二级科室
     */
    private void findAllDepartments(String checkDepartmentsName) {
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor query = readableDatabase.query("departments", null, "departments_id != ?", new String[]{"0"}, null, null, null);
        List<String> departmentsList = new ArrayList<>(10);
        while (query.moveToNext()) {
            String departmentsName = query.getString(1);
            departmentsList.add(departmentsName);
        }
        setSpinnerText(departmentsType,departmentsList,checkDepartmentsName);
//        将当前默认科室赋值给全局变量
        departmentsTypeToStr = checkDepartmentsName;

    }

    /**
     * 查询所有职务
     */
    private void findAllPosition(String checkPositionName) {
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor query = readableDatabase.query("position", null, null, null, null, null, null);
        List<String> positionList = new ArrayList<>(6);
        while (query.moveToNext()) {
            String positionName = query.getString(1);
            positionList.add(positionName);
        }
        setSpinnerText(positionType,positionList,checkPositionName);
//        将当前默认职务赋值给全局变量
        positionTypeToStr = checkPositionName;

    }

    /**
     * 下拉框赋值
     * @param spinner 下拉框
     * @param positionList 数据集
     */
    public void setSpinnerText(Spinner spinner, List<String> positionList,String checkName){
        ArrayAdapter<String> adapter= new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,positionList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);//给下拉框赋值
        int count = adapter.getCount();
        for (int i = 0; i < count; i++) {
            if (checkName.equals(adapter.getItem(i))) {
                spinner.setSelection(i,true); // 默认选中值
                break;
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            更新医生信息
            case R.id.updateDoctorBtn:
                updateDoctorInfo();
                break;
            default:

        }
    }

    /**
     * 更新医生信息
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @SuppressLint("LongLogTag")
    private void updateDoctorInfo() {
        String doctorId2 = doctorId.getText().toString();
        String doctorUserName = userName.getText().toString();
        String doctorPhone = phone.getText().toString();
        String doctorIdNumber = idNumber.getText().toString();
        String doctorAge = age.getText().toString();
//        判断选择的性别
        String doctorSex = "0";
        if (woman.isChecked()) {
            doctorSex = "1";
        }
        String doctorAddress = address.getText().toString();
        String doctorSpecialty = specialty.getText().toString();
        String doctorDescribe = describe.getText().toString();
        Boolean check = checkDoctorData(doctorId2,doctorUserName,doctorPhone,doctorIdNumber,doctorAge,doctorSex,doctorAddress,doctorSpecialty,doctorDescribe);
        if (check) { //校验通过
            //        打开数据库
            SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//        校验职务是否存在
            Integer positionId = null;
            Cursor query = readableDatabase.query("position", null, "name = ?", new String[]{positionTypeToStr}, null, null, null);
            while (query.moveToNext()) {
                try {
                    positionId = Integer.valueOf(query.getString(0));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    Log.e("DoctorUpdateActivity.java", "数据不能转化为数字,请检查！");
                }
            }
//          检查医生所属科室
            Integer departmentsId = null;
            Cursor queryDepartments = readableDatabase.query("departments", null, "name = ?", new String[]{departmentsTypeToStr}, null, null, null);
            while (queryDepartments.moveToNext()) {
                try {
                    departmentsId = Integer.valueOf(queryDepartments.getString(0));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    Log.e("DoctorUpdateActivity.java", "数据不能转化为数字,请检查！");
                }
            }
            //                    封装需要新增的医生详情信息
            ContentValues contentValues = new ContentValues();
            contentValues.put("username",doctorUserName);
            contentValues.put("position_id",positionId);
            contentValues.put("departments_id",departmentsId);
            contentValues.put("specialty",doctorSpecialty);
            contentValues.put("describe",doctorDescribe);
            contentValues.put("update_time", DateUtil.dateString(new Date()));
            long doctorDetailsId = readableDatabase.update("doctor_details", contentValues,"id = ? ",new String[]{doctorId2});
//                    封装需要新增的医生用户信息
            ContentValues contentUserValues = new ContentValues();
            contentUserValues.put("username",doctorUserName);
            contentUserValues.put("phone",doctorPhone);
            contentUserValues.put("password","123456"); // 默认密码
            contentUserValues.put("type",1); // 1:医生
            contentUserValues.put("sex",doctorSex);
            contentUserValues.put("age",doctorAge);
            contentUserValues.put("id_number",doctorIdNumber);
            contentUserValues.put("address",doctorAddress);
            contentUserValues.put("doctor_id",doctorId2);
            contentUserValues.put("update_time", DateUtil.dateString(new Date()));
            long userId = readableDatabase.update("user",  contentUserValues," doctor_id = ? ",new String[]{doctorId2});
            if (userId == 1 && doctorDetailsId == 1) {
                toast = ToastUtil.toastHint(toast, DoctorUpdateActivity.this, "更新医生成功，请稍后查看！");
                return;
            }

        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private Boolean checkDoctorData(String doctorId2, String doctorUserName, String doctorPhone, String doctorIdNumber, String doctorAge, String doctorSex, String doctorAddress, String doctorSpecialty, String doctorDescribe) {
        //        校验医生编号
        if (doctorId2.equals("") || doctorId2.equals(null) || doctorId2 == null) {
            toast = ToastUtil.toastHint(toast,DoctorUpdateActivity.this,"医生编号不能为空！");
            return false;
        }

        if (!RegexUtil.checkChinese(doctorUserName)) {
            toast = ToastUtil.toastHint(toast,DoctorUpdateActivity.this,"医生姓名只支持中文！");
            return false;
        }
        if (!RegexUtil.checkMobile(doctorPhone)) {
            toast = ToastUtil.toastHint(toast,DoctorUpdateActivity.this,"请输入正确的手机号！");
            return false;
        }
        if (!RegexUtil.checkIdCard(doctorIdNumber)) {
            toast = ToastUtil.toastHint(toast,DoctorUpdateActivity.this,"请输入正确的身份证号！");
            return false;
        }
        if (!RegexUtil.checkDigitz(doctorAge)) {
            toast = ToastUtil.toastHint(toast,DoctorUpdateActivity.this,"请输入正确的年龄！");
            return false;
        }
        if (!doctorSex.equals("0") && !doctorSex.equals("1")) {
            toast = ToastUtil.toastHint(toast,DoctorUpdateActivity.this,"请选择性别！");
            return false;
        }
        if (doctorAddress.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorUpdateActivity.this,"请输入地址！");
            return false;
        }

        if (doctorSpecialty.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorUpdateActivity.this,"请输入擅长！");
            return false;
        }

        if (doctorDescribe.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorUpdateActivity.this,"请输入简介！");
            return false;
        }

        //        校验信息是否存在
//        打开数据库
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//        校验手机号是否已被注册(不包含自己)
        String buyerId = null;
        Cursor query = readableDatabase.query("user", null, "phone = ? and doctor_id != ? ", new String[]{doctorPhone,doctorId2}, null, null, null);
        while (query.moveToNext()) {
            buyerId = query.getString(0);
        }
//        如果存在值，表示已经被注册
        if (Objects.nonNull(buyerId)) {
            toast = ToastUtil.toastHint(toast,DoctorUpdateActivity.this,"该手机号已被注册或不能重复！");
            return false;
        }
        //        校验身份证号是否已被注册(不包含自己)
        String buyerId2 = null;
        Cursor query2 = readableDatabase.query("user", null, "id_number = ? and doctor_id != ? ", new String[]{doctorIdNumber,doctorId2}, null, null, null);
        while (query2.moveToNext()) {
            buyerId2 = query2.getString(0);
        }
//        如果存在值，表示已经被注册
        if (Objects.nonNull(buyerId2)) {
            toast = ToastUtil.toastHint(toast,DoctorUpdateActivity.this,"该身份证号已被注册或不能重复！");
            return false;
        }
        return true;
    }

    /**
     * 重写onKeyDown()方法来拦截用户单击后退按钮事件
     * @param keyCode 按键标识
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        判断按下的是否为后退按键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            返回上一页标识是否刷新
//            setResult(RESULT_OK,new Intent());
//            重新跳转到医生管理页
            startActivityForResult(new Intent(DoctorUpdateActivity.this,DockerAdminActivity.class),RESULT_OK);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}